import { useRef, useState } from "react";
import * as CryptoJSAlias from "crypto-js";
export default function CryptoJS() {
    const ref = useRef(null);
    // 加密密钥
    const key = "secret key";
    // 加密数据
    const [data] = useState("Hello, World!");
    // 初始化向量（IV），用于增加加密的强度
    const iv = "0102030405060708090a0b0c";
    const [code, setCode] = useState("");
    const encryptedData = () => {
        // encrypt函数最后一个参数对象不写也可以进行加密
        let encryptedRes = CryptoJSAlias.AES.encrypt(data, key, {
            iv: iv,
            mode: CryptoJSAlias.mode.CBC, // 指定加密模式为CBC（Cipher Block Chaining）模式
            padding: CryptoJSAlias.pad.ZeroPadding, //指定填充方案为ZeroPadding，这意味着在加密前会使用零填充数据以满足块大小
        }).toString();
        console.log("加密后的结果：", encryptedRes);
        setCode(encryptedRes);
        if (ref.current) {
            (ref.current as HTMLDivElement).innerText = encryptedRes;
        }
    };
    const decryptedData = () => {
        let decryptedRes = CryptoJSAlias.AES.decrypt(code, "secret key").toString(CryptoJSAlias.enc.Utf8);
        if (ref.current) {
            (ref.current as HTMLDivElement).innerText = decryptedRes;
        }
    };

    return (
        <div>
            <button className="returnButton">
                <a href="/">点击返回主菜单</a>
            </button>
            <h1>CryptoJS</h1>
            <p>
                <a href="https://cryptojs.gitbook.io/docs/" target="_back">查看官网说明</a>
            </p>
            <button onClick={encryptedData}>加密</button>
            <button onClick={decryptedData}>解密</button>
            <div>
                <p style={{ fontSize: "36px" }}>
                    <span>需要加密数据data:</span>
                    {data}
                </p>
                <p style={{ fontSize: "36px" }}>
                    <span>生成hash code:</span>
                    {code}
                </p>
            </div>
            <p ref={ref}></p>
        </div>
    );
}
